Computer Science 161.01

November 11th 2019

JavaScript Arrays

 

 

 

JavaScript Arrays:  The Basics

 

In high-level programming languages such as JavaScript, an Array provides a mechanism for storing an entire

list of items, all of the same type (e.g a list of strings, or a list of numbers) with one name that you can use to

refer to the entire collection.

 

For example,

            list = new Array(21, 12, 89, 61, 5, 33);

creates an Array  named list with 6 items, all of them numbers.

 

In JavaScript, the expression list.length will always give us the number of items in list,

in this case, 6.

 

Obviously, this whole idea isn’t very useful if we can’t access the individual items in the Array named list.

The way languages like JavaScript enable us to do this is with the idea of indexing (or, some say subscripting).

 

Remember that list refers to the entire collection of six numbers. 

But how do I refer to the leftmost number 21?

 

We’ll think of it as item #0 in the Array named list , or better yet  list[0].

Thus list[0] is 21  ,  list[1] is 12  ,  list[2] is 89  , and so on.

Notice that the last (rightmost) number in list is 33 which corresponds to list[5] .

This is not surprising, since remember that list.length is 6 and the indices start at 0.

 

As a second example, consider

             foods = new Array("bread", "milk", "ice cream", "bananas", "asparagus");           

 

What is foods.length?   That’s right, it is 5.

 

What is foods[0] ? 

If you said  bread then treat yourself to a bowl of foods[2].

 

Here’s something interesting.  What is foods[1].length?

Well, foods[1] is milk so you should expect that foods[1].length is 4 ,

which is the number of symbols in milk.

 

Visiting every member of an Array

 

Now that I have all of these good foods in an Array, I’d really like to ‘visit’, left to right, each member of the Array

(an odd buffet table, eh?) and declare

 

"I like bread"

"I like milk"

"I like ice cream"

"I like bananas"

"I like asparagus"

 

If I’m programming this, I’m remembering that I just learned how to access each individual item.

So I know, in long-hand, that the following is what I really want to do:

 

alert("I like " + foods[0]);

alert("I like " + foods[1]);

alert("I like " + foods[2]);

alert("I like " + foods[3]);

alert("I like " + foods[4]);

 

What I should do now is recognize that I can have just one alert statement in a loop!

 

That’s because each of the 5 statements above looks like 

  alert("I like " + foods[i]);  

where    i = 0, then 1, then 2, then 3, then 4.

 

Hey, that’s it!

 

i=0; //start with foods[0], I like bread!

 

while (i < 5) {

     alert("I like " + foods[i]); //I like current foods item

     i++; //move to next

}  

 

At this point, you must convince yourself that this program segment does exactly what the five alerts did prior.

 

This code I have just written works fine – provided that foods.length is 5.

But what if I add some items to my foods Array, making it bigger?

I won’t get beyond foods[4] with the program I just wrote, even though I might later have 100 items ending with foods[99] !

 

Programs like this need to be general and flexible.

How many items in the foods array should we visit, if we wish to visit all of them?

The answer lies in foods.length .

 

So here’s a better program:

 

foods = new Array("bread", "milk", "ice cream", "bananas", "asparagus");

i=0;                //start with foods[0], I like bread!

N = foods.length;   //save the length of the foods Array into N

 

while (i < N) { //for as many items as is in the array

     alert("I like " + foods[i]); //I like current foods item

     i++;                  //move to next foods item

}  

 

Exercises

1. Copy this into the scratchpad site and see how it works!

2. Try changing the Array, but adding more items and deleting items, and see if the program still works.

3. Modify the program so that it says it likes all but the last item, and have the program say that it hates the last item.

 

 

Our Pattern for Visiting Every Item in an Array

 

Every array problem in which you are asked to ‘visit’ each item will have the following look:

 

list = new Array(…); //we’ll have some Array which we might call ‘list’

 

N = list.length; //since we want to visit this many items

i = 0;           //starting with the item at the left

 

while (i < N) {    //so we visit every item in turn

   //do something with list[i]

   //whether it be an alert or an if statement or summing!

 

   i++;  //move to the right one spot to point at next item

}

 

 

Let’s try this approach out:

 

Problem 1:  Write a program that sums all the numbers in an array.

Solution (I am copying that pattern from above and adapting!)

 

list = new Array(61, 18, 20, 3, 9, 12, 24, 10);

 

N = list.length; //since we want to visit this many items

i = 0;           //starting with the item at the left

 

sum = 0; //ok, extra because I want to compute a sum of the numbers

         //the sum is initially 0

 

while (i < N) {    //so we visit every item in turn

   //do something with list[i]

   sum += list[i]; //the current list item gets added to sum

 

   i++;  //move to the right one spot to point at next item

}

sum  //this reports the sum in the bottom part of the scratchpad

 

Copy this into the scratchpad site and see how it works, making changes, as always to the array,

and seeing whether the program adapts to the changes.

 

 

Problem 2:  Write a program that counts the numbers in the array that are less than 20.

Solution: (same pattern!)

 

list = new Array(61, 18, 20, 3, 9, 12, 24, 10);

 

N = list.length; //since we want to visit this many items

i = 0;           //starting with the item at the left

 

count = 0; //ok, extra because I want to count how many numbers

         //are less than 20.  Initially the count is set to 0.

 

while (i < N) {    //so we visit every item in turn

   //do something with list[i]

   if (list[i] < 20)  //if the current list item is less than 20

      count++;        //then add 1 to the count!

 

   i++;  //move to the right one spot to point at next item

}

count  //this reports the count in the bottom part of the scratchpad

 

Copy this into the scratchpad site and see how it works, making changes, as always to the array,

and seeing whether the program adapts to the changes.

 

 

Problem 3:  Write a program that displays to the screen only the even list items.

Solution: (same pattern!)

 

list = new Array(61, 18, 20, 3, 9, 12, 24, 10);

 

N = list.length; //since we want to visit this many items

i = 0;           //starting with the item at the left

 

while (i < N) {    //so we visit every item in turn

   //do something with list[i]

   if (list[i] % 2 == 0)  //if the current list item is even

       alert(list[i] + " is even!");     //then tell us so!

 

   i++;  //move to the right one spot to point at next item

}

alert("DONE");         

 

 

Exercises

1. Start with our favorite Array of food items

foods = new Array("bread", "milk", "ice cream", "bananas", "asparagus");

and write a program that will sum the lengths of the words in the Array. (See Problem 1).

 

2. Start with our favorite Array of food items

foods = new Array("bread", "milk", "ice cream", "bananas", "asparagus");

and write a program that will count the number of words in the Array that have fewer than 8 symbols (See Problem 2).